package com.attilax.wechat;

 

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

//import com.jade.laiding.order.order.Order;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.xmlbeans.XmlBeans;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.attilax.exception.ExUtil;
import com.attilax.io.filex;
import com.attilax.json.AtiJson;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by tusm on ��Ԫ15-10-27.
 */
public class WeChatPayUtil {

    private static final String WeChat_APP_ID="#####################";
    private static final String WeChat_MCH_ID="#####################";
    private static final String WeChat_API_KEY="####################";


    //΢��֧����һ�����ȴ�΢�ŵķ�������ȡprepayId
//    public static String getPrepayId(String url,Order order){
//        Map<String,String> xml=new HashMap<String,String>();
//        String prePayId = "";
//
//        if(order != null){
//            String entity = genProductArgs(order);
//            byte[] buf = Util.httpPost(url, entity);
//            if(buf != null){
//
//                String content = new String(buf);
//                //Log.e("orion", content);
//                try {
//                    Document doc = (Document)DocumentHelper.parseText(content);
//                    Element root = doc.getRootElement();
//                    List<Element> list = root.elements();
//                    for (Element e : list) {
//                        xml.put(e.getName(), e.getText());
//                    }
//                } catch (DocumentException e) {
//                    e.printStackTrace();
//                }
//                if(xml != null){
//                    prePayId = xml.get("prepay_id");
//                    return prePayId;
//                }
//            }
//        }
//
//        return null;
//    }


//
//    //�ڶ���������prepayId����ǩ������
//    public static PayReq genPayReq(PayReq req,String prePayId) {
//        req.setAppId(WeChatPayUtil.WeChat_APP_ID);
//        req.setPartnerId(WeChatPayUtil.WeChat_MCH_ID);
//        req.setPrepayId(prePayId);
//        req.setPackageValue("Sign=WXPay");
//        req.setNonceStr(genNonceStr());
//        req.setTimeStamp(String.valueOf(genTimeStamp()));
//
//
//        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
//        signParams.add(new BasicNameValuePair("appid", req.getAppId()));
//        signParams.add(new BasicNameValuePair("noncestr", req.getNonceStr()));
//        signParams.add(new BasicNameValuePair("package",req.getPackageValue()));
//        signParams.add(new BasicNameValuePair("partnerid",req.getPartnerId()));
//        signParams.add(new BasicNameValuePair("prepayid",req.getPrepayId()));
//        signParams.add(new BasicNameValuePair("timestamp", req.getTimeStamp()));
//
//        req.setSign(genAppSign(signParams));
//
//        return req;
//        //Log.i("orion", signParams.toString());
//
//    }

    //������������֧���ӿ�֧��
   /* public static void Pay(IWXAPI msgApi,PayReq req){
            msgApi.sendReq(req);
    }*/


    /**
     * ƴ�Ӳ���
     * @param order
     * @return
     */
//    private static String genProductArgs(Order order) {
//        StringBuffer xml = new StringBuffer();
//        try {
//            String	nonceStr = genNonceStr();
//
//            xml.append("</xml>");
//            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
//            packageParams.add(new BasicNameValuePair("appid", WeChatPayUtil.WeChat_APP_ID));
//            packageParams.add(new BasicNameValuePair("body", "����"));//��Ʒ��������Ʒ��֧������Ҫ����������
//            packageParams.add(new BasicNameValuePair("mch_id", WeChatPayUtil.WeChat_MCH_ID));
//            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));//����ַ�����������32λ������
//            packageParams.add(new BasicNameValuePair("notify_url", "http://����IP:8182/client/order/editOrderWxPayStatus"));//����΢��֧���첽֪ͨ�ص���ַ.����
//            packageParams.add(new BasicNameValuePair("out_trade_no",order.getId()+""));//�̻�ϵͳ�ڲ��Ķ�����,32���ַ��ڡ��ɰ�����ĸ,����
//            packageParams.add(new BasicNameValuePair("spbill_create_ip",order.getIp()));//APP����ҳ֧���ύ�û���ip.����
//            packageParams.add(new BasicNameValuePair("total_fee", (int)(order.getFinalAmount()*100)+""));//�����ܽ�ֻ��Ϊ����.����
//            packageParams.add(new BasicNameValuePair("trade_type", "APP"));//ȡֵ���£�JSAPI��NATIVE��APP��WAP,����
//
//
//            String sign = genPackageSign(packageParams);
//            packageParams.add(new BasicNameValuePair("sign", sign));//ǩ��
//
//
//            String xmlstring =toXml(packageParams);
//
//            xmlstring = new String(xmlstring.getBytes("UTF-8"), "ISO-8859-1");
//
//            return xmlstring;
//
//        } catch (Exception e) {
//            //Log.e("e", "genProductArgs fail, ex = " + e.getMessage());
//            return null;
//        }
//    }

    /**
     * ƴ���첽֪ͨ�ɹ�֪ͨ΢�Ų���
     * @return
     */
    public static String returnCodeSUCCESS() {
        StringBuffer xml = new StringBuffer();
        try {
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("return_code", "SUCCESS"));//SUCCESS��ʾ�̻�����֪ͨ�ɹ���У��ɹ�����
            String xmlstring =toXml(packageParams);
            xmlstring = new String(xmlstring.getBytes("UTF-8"), "ISO-8859-1");
            return xmlstring;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * ƴ���첽֪ͨʧ��֪ͨ΢�Ų���
     * @return
     */
    public static String returnCodeFAIL() {
        StringBuffer xml = new StringBuffer();
        try {
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("return_code", "FAIL"));//FAILʧ��
            String xmlstring =toXml(packageParams);
            xmlstring = new String(xmlstring.getBytes("UTF-8"), "ISO-8859-1");
            return xmlstring;
        } catch (Exception e) {
            return null;
        }
    }


public static void main(String[] args) {
	System.out.println("aa");
	//XmlBeans
}

    /**
     ����ǩ��
     */

    private static String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(WeChatPayUtil.WeChat_API_KEY);


        String packageSign = ""; //MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        //Log.e("orion",packageSign);
        return packageSign;
    }

    /**
     * ת����String��ʽ��xml
     * @param params
     * @return
     */
    private static String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<"+params.get(i).getName()+">");


            sb.append(params.get(i).getValue());
            sb.append("</"+params.get(i).getName()+">");
        }
        sb.append("</xml>");

        //Log.e("orion",sb.toString());
        return sb.toString();
    }

    /**
     * ������key��appǩ��
     * @param params
     * @return
     */
    private static String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(WeChatPayUtil.WeChat_API_KEY);

        String appSign ="";// MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        //Log.e("orion",appSign);
        return appSign;
    }

    /**
     * ʱ���
     * @return
     */
    private static long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * ����ַ���
     * @return
     */
    private static  String genNonceStr() {
        Random random = new Random();
        return "";//MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    public static String getIp2(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //��η���������ж��ipֵ����һ��ip������ʵip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
    
    
    /**
     * @api {post} /order/editOrderPayStatus �޸Ķ���֧��״̬(֧����)
     * @apiName editOrderPayStatus API
     * @apiGroup Order
     * @apiDescription �޸Ķ���֧��״̬(֧����)
     * @apiVersion 0.1.0
     * @apiParam {String} id �������.
     * @apiParam {String} orderStatus ����״̬
     * @apiParam {String} PayStatus ֧��״̬ Paying,Paied,PartPaied,PartRefund,Refund
     * @apiParam {String} ShipStatus  Pending("0"),Shipped("1"),PartPending("2"),PartShipped("3"),Returned("4")
     */
//    @RequestMapping(value = "/editOrderPayStatus", method = RequestMethod.POST)
 
    public   DisplayData editOrderPayStatus_alipay(HttpServletRequest request,HttpServletResponse response) {
        Order oldorder = null;
        try {
            String trade_status=request.getParameter("trade_status");//����״̬
            Long trade_no=Long.parseLong(request.getParameter("out_trade_no"));//���׶�����
            float total_fee=Float.parseFloat(request.getParameter("total_fee"));//�����ܽ��
           // oldorder=orderManager.get(Order.class,trade_no);
           float FinalAmount = 0;//oldorder.getFinalAmount();//���ݿⶩ�����
            if("TRADE_SUCCESS".equals(trade_status)&&trade_status!=null){
                if(null!=oldorder){
                    if(total_fee==FinalAmount){
                        //��֧������״̬����
//                        if ((oldorder.getOrderStatus() == OrderStatus.Active) && (oldorder.getPayStatus() == PayStatus.Paying || oldorder.getPayStatus() == PayStatus.PartPaied) && (oldorder.getShipStatus() == ShipStatus.Pending)) {
//                            oldorder.setOrderStatus(OrderStatus.Active);//��֧��
//                            oldorder.setPayStatus(PayStatus.Paied);
//                            oldorder.setShipStatus(oldorder.getShipStatus());
//                            orderManager.update(oldorder);
//                            response.getWriter().println("success");	//�벻Ҫ�޸Ļ�ɾ��
//                        }
                    }else{
                        response.getWriter().println("fail");//�벻Ҫ�޸Ļ�ɾ��
                    }
                }
            }else{
                response.getWriter().println("fail");//�벻Ҫ�޸Ļ�ɾ��
            }
          //  return new DisplayData(request,StatusCode.SUCCESS,"inf.jade.bss.commons.success",oldorder);
        } catch (Exception e) {
         //   return new DisplayData(request, StatusCode.FAIL,e.getMessage());
        }
		return null;
    }



    /**
     * @api {post} /order/editOrderWxPayStatus �޸Ķ���֧��״̬(΢��)
     * @apiName editOrderWxPayStatus API
     * @apiGroup Order
     * @apiDescription �޸Ķ���֧��״̬(΢��)
     * @apiVersion 0.1.0
     * @apiParam {String} id �������.
     * @apiParam {String} orderStatus ����״̬
     * @apiParam {String} PayStatus ֧��״̬ Paying,Paied,PartPaied,PartRefund,Refund
     * @apiParam {String} ShipStatus  Pending("0"),Shipped("1"),PartPending("2"),PartShipped("3"),Returned("4")
     */
  //  @RequestMapping(value = "/editOrderWxPayStatus", method = RequestMethod.POST)
    public   Map editOrderWxPayStatus(HttpServletRequest request,HttpServletResponse response) {
        Order oldorder = null;
      
                // ����������洢��HashMap��
                Map map = new HashMap();
                // ��request��ȡ��������
                InputStream inputStream = null;
				try {
					inputStream = request.getInputStream();
				} catch (IOException e3) {
					ExUtil.throwExV2(e3);
				}
                // ��ȡ������
                SAXReader reader = new SAXReader();
                Document document = null;
				try {
					document = reader.read(inputStream);
					
				} catch (DocumentException e2) {
					//filex.save_safe(AtiJson.toJson(e2), "c:\\0rechglog\\"+filex.getUUidName()+".txt");
					ExUtil.throwExV2(e2);
				}
                // �õ�xml��Ԫ��
                Element root = document.getRootElement();
               // root.getTextTrim()()
            	filex.save_safe(AtiJson.toJson(root), "c:\\0rechglog\\"+filex.getUUidName()+".txt");
                // �õ���Ԫ�ص������ӽڵ�
                List<Element> list = root.elements();
                // ���������ӽڵ�
                for (Element e : list){
                    map.put(e.getName(), e.getText());
                }
                filex.save_safe(AtiJson.toJson(map), "c:\\0rechglog\\"+filex.getUUidName()+".txt");
                try {
					inputStream.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
                inputStream=null;
                return map;
             
      
    }

    
}
